package test.com.stained.white.goat.random;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import com.stained.white.goat.random.RandomUtils;

/**
 * 乱数生成クラステストスレッド.
 * @author stained white goat
 *
 */
public class RandomThread extends Thread {

    /** 乱数範囲. */
    private int range;
    /** デバッグ有無. */
    private boolean isDebug;
    /** 分布集合. */
    private Map<String, Integer> valueCounter;

    /**
     * Constructor.
     * @param range 乱数範囲
     * @param isDebug デバッグ有無（true : デバッグ / false : デバッグ以外）
     */
    public RandomThread(int range, boolean isDebug) {
        this.range = range;
        this.isDebug = isDebug;
    }

    @Override
    public void run() {
        valueCounter = new TreeMap<String, Integer>(new Comparator<String>() {
            @Override
            public int compare(String arg0, String arg1) {
                return arg0.compareTo(arg1);
            }
        });

        while (true) {
            createDistributionMap();
            if (valueCounter.size() < range) {
                continue;
            }
            break;
        }
        createDistribution();
    }

    /**
     * 分布図作成.
     */
    private void createDistributionMap() {
        String value = getValue();
        if (!valueCounter.containsKey(value)) {
            valueCounter.put(value, Integer.valueOf(1));
            return;
        }
        valueCounter.put(
                value, Integer.valueOf(valueCounter.get(value).intValue() + 1));
    }

    /**
     * 分布図出力.
     */
    protected void createDistribution() {
        if (!isDebug) {
            return;
        }

        StringBuilder b = new StringBuilder();

        String line = System.getProperty("line.separator");
        for (Iterator<Entry<String, Integer>> it =
            valueCounter.entrySet().iterator(); it.hasNext();) {
            Entry<String, Integer> entry = it.next();
            b.append(entry.getKey()).append("=");
            for (int i = 0, max = entry.getValue().intValue(); i < max; i++) {
                b.append("|");
            }
            b.append(line);
        }
        System.out.println(b.toString());
    }

    /**
     * 分布キー取得.
     * @return 分布キー
     */
    protected String getValue() {
        return String.format("%6d", getRandomNumber());
    }

    /**
     * 乱数取得.
     * @return 乱数
     */
    private int getRandomNumber() {
        return RandomUtils.getRandomNumber(range);
    }

    /**
     * 分布集合数取得.
     * @return 分布集合数
     */
    public int getValueCount() {
        if (valueCounter == null) {
            return 0;
        }
        return valueCounter.size();
    }
}
